package com.ruanmeng.fragment;

import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.view.Display;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.com.ruanmeng.demon.SYM;
import com.com.ruanmeng.utils.PreferencesUtils;
import com.com.ruanmeng.view.MyListView;
import com.example.lenovo.weiyi.HealthMessXQActivity;
import com.example.lenovo.weiyi.LunBoXQActivity;
import com.example.lenovo.weiyi.NoticeXQActivity;
import com.example.lenovo.weiyi.R;
import com.jude.rollviewpager.OnItemClickListener;
import com.jude.rollviewpager.RollPagerView;
import com.jude.rollviewpager.adapter.LoopPagerAdapter;
import com.jude.rollviewpager.hintview.ColorPointHintView;
import com.yolanda.nohttp.NoHttp;
import com.yolanda.nohttp.rest.Request;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import nohttp.CallServer;
import nohttp.CustomHttpListener;
import share.Const;
import share.HttpIP;


public class ShouYeFragment extends Fragment {


    @BindView(R.id.ic_fragment_home_lunbo)
    RollPagerView mLoopViewPager;
    @BindView(R.id.li_sy_jkzs)
    LinearLayout liSyJkzs;
    @BindView(R.id.mlist_sy_jkzs)
    MyListView mlistSyJkzs;
//    @BindView(R.id.rl_sy_refresh)
//    SwipeRefreshLayout mRefresh;
    ArrayList<SYM.ObjectBean.CourseBean> Temp_list = new ArrayList<>();
    @BindView(R.id.view_sy)
    View viewSy;
    private View fview;
    private HealthAdapter adapter;
    private SYM model;
    private LoopAdapter mLoopAdapter;

    public static ShouYeFragment instantiation() {
        ShouYeFragment fragment = new ShouYeFragment();
        return fragment;
    }

    @Override
    public View onCreateView(LayoutInflater inflater,
                             @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        fview = inflater.inflate(R.layout.shouye_fragment_layout, null);
        ButterKnife.bind(this, fview);
        init(fview);
        getData(true);
        return fview;
    }

    @Override
    public void onResume() {
        super.onResume();
        getData(false);
    }

    public void init(View v) {
//        mRefresh.setColorSchemeResources(R.color.MainColor);
//        mRefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
//            @Override
//            public void onRefresh() {
//                getData();
//            }
//        });
        //轮播图
        mLoopViewPager.setAdapter(mLoopAdapter = new LoopAdapter(getActivity(),mLoopViewPager));
        mLoopViewPager.setHintView(new ColorPointHintView(getActivity(), getResources().getColor(R.color.MainColor),getResources().getColor(R.color.White)));
//        mLoopViewPager.setHintView(new IconHintView(getActivity(), R.drawable.banner_yuan_pre, R.drawable.banner_yuan));
        WindowManager windowManager = getActivity().getWindowManager();
        Display display = windowManager.getDefaultDisplay();
        int screenWidth = display.getWidth();
        int hei = (int) (screenWidth / 2);
        LinearLayout.LayoutParams rlay_params = new LinearLayout.LayoutParams(
                screenWidth, hei);
        mLoopViewPager.setLayoutParams(rlay_params);
        //健康知识
        adapter = new HealthAdapter(Temp_list);
        mlistSyJkzs.setAdapter(adapter);
        mlistSyJkzs.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
                Intent in = new Intent(getActivity(), HealthMessXQActivity.class);
                in.putExtra("id", Temp_list.get(position).getCourseId());
                startActivity(in);
            }
        });
    }

    private void getData(Boolean b) {
        Request<String> mRequest = NoHttp.createStringRequest(HttpIP.SY, Const.POST);
        mRequest.addHeader("token", PreferencesUtils.getString(getActivity(), "uid"));
        CallServer.getRequestInstance().add(getActivity(), 0, mRequest,
                new CustomHttpListener(getActivity(), true, SYM.class) {

                    @Override
                    public void doWork(Object data, boolean isOne) {
                        model = ((SYM) data);
                        //轮播图
                        final List<SYM.ObjectBean.SlidersBean> Temp_Lunbo = model.getObject().getSliders();
                        getActivity().runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                mLoopAdapter.setImgs(Temp_Lunbo);
                            }
                        });
                        mLoopViewPager.setOnItemClickListener(new OnItemClickListener() {
                            @Override
                            public void onItemClick(int position) {
                                if (Temp_Lunbo.get(position).getHref() != null && !TextUtils.isEmpty(Temp_Lunbo.get(position).getHref())) {
                                    Uri uri = Uri.parse(Temp_Lunbo.get(position).getHref());
                                    Intent intent = new Intent(Intent.ACTION_VIEW, uri);
                                    startActivity(intent);
                                } else if (!TextUtils.isEmpty(model.getObject().getSliders().get(position).getContent())) {
                                    Intent in = new Intent(getActivity(), LunBoXQActivity.class);
                                    in.putExtra("title", Temp_Lunbo.get(position).getSliderTitle());
                                    in.putExtra("content", Temp_Lunbo.get(position).getContent());
                                    startActivity(in);
                                }
                            }
                        });
                        //健康知识
                        Temp_list.clear();
                        Temp_list.addAll(model.getObject().getCourse());
                        adapter.notifyDataSetChanged();
//                        //关于弹出消息
//                        if (model.getObject().getNotice() != null) {
//                            if (TextUtils.isEmpty(PreferencesUtils.getString(getActivity(), "notice_date"))) {//第一次弹出
//                                ShowPop();
//                            } else {
//                                if (!model.getObject().getNotice().getCreateDate().equals(PreferencesUtils.getString(getActivity(), "notice_date"))) {
//                                    ShowPop();
//                                }
//                            }
//                        }
//                        PreferencesUtils.putString(getActivity(), "notice_date", model.getObject().getNotice().getCreateDate());
                    }

                    @Override
                    public void onFinally(JSONObject obj) throws JSONException {
                        super.onFinally(obj);
//                        mRefresh.setRefreshing(false);
                    }
                }, true, b);
    }

    /**
     * 健康知识
     */
    class HealthAdapter extends BaseAdapter {
        private List<SYM.ObjectBean.CourseBean> list;

        public HealthAdapter(List<SYM.ObjectBean.CourseBean> list) {
            this.list = list;
        }

        @Override
        public int getCount() {
            return list.size();
        }

        @Override
        public Object getItem(int position) {
            return list.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(final int position, View v, ViewGroup parent) {
            v = getActivity().getLayoutInflater().inflate(R.layout.item_text, null);
            TextView tv_text_tilte = (TextView) v.findViewById(R.id.tv_text_tilte);
            View view_ban = (View) v.findViewById(R.id.view_text_ban);
            View view_man = (View) v.findViewById(R.id.view_text_man);
            tv_text_tilte.setText(list.get(position).getTitle());
            if (position == Temp_list.size() - 1) {
                view_ban.setVisibility(View.GONE);
                view_man.setVisibility(View.VISIBLE);
            } else {
                view_ban.setVisibility(View.VISIBLE);
                view_man.setVisibility(View.GONE);
            }
            return v;
        }

    }

  /*  public void doClick(View v) {
        switch (v.getId()) {
            case R.id.li_sy_jkzs://健康知识
                Intent in = new Intent(getActivity(), HealthMessListActivity.class);
                startActivity(in);
                break;
        }
    }*/

    /**
     * 强制完善个人资料
     */
    public void ShowPop() {
        // 加载布局
        LayoutInflater inflater = LayoutInflater
                .from(getActivity());
        View view = inflater.inflate(R.layout.pop_notice, null);
        TextView tv_notice_title = (TextView) view.findViewById(R.id.tv_notice_title);
        TextView tv_notice_content = (TextView) view.findViewById(R.id.tv_notice_content);
        TextView tv_notice_cancel = (TextView) view.findViewById(R.id.tv_notice_cancel);
        TextView tv_see = (TextView) view.findViewById(R.id.tv_see);
        tv_notice_title.setText(model.getObject().getNotice().getTitle());
        tv_notice_content.setText(model.getObject().getNotice().getContent());
        // 创建popupwindow对话框
        final PopupWindow pop = new PopupWindow(view, ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.MATCH_PARENT);
        pop.setFocusable(true);// 必须有，因为要获得焦点进行输入
        // 设置此参数，点击外边可消失
        pop.setBackgroundDrawable(new BitmapDrawable());
        // 点击其他除了popupwindow对话框的地方就可使popupwindow对话框消失
        pop.setOutsideTouchable(true);
        //pop.showAtLocation(liFr, Gravity.CENTER, 0, 0);// 显示位置以某控件为中心
        if (Build.VERSION.SDK_INT >= 24) {
            int[] a = new int[2];
            viewSy.getLocationInWindow(a);
            pop.showAtLocation((getActivity()).getWindow().getDecorView(), Gravity.NO_GRAVITY, 0, a[1] + viewSy.getHeight());
        } else {
            pop.showAsDropDown(viewSy);
        }
        tv_notice_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                pop.dismiss();
            }
        });
        tv_see.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                pop.dismiss();
                Intent in = new Intent(getActivity(), NoticeXQActivity.class);
                in.putExtra("title", model.getObject().getNotice().getTitle());
                in.putExtra("content", model.getObject().getNotice().getContent());
                in.putExtra("time", model.getObject().getNotice().getCreateDate());
                startActivity(in);

            }
        });
    }

    public class LoopAdapter extends LoopPagerAdapter {

        private Context context;
        List<SYM.ObjectBean.SlidersBean> imgs=new ArrayList<>();

        public void setImgs( List<SYM.ObjectBean.SlidersBean> imgs) {
            this.imgs = imgs;
            notifyDataSetChanged();
        }

        public LoopAdapter(Context context, RollPagerView viewPager) {
            super(viewPager);
            this.context = context;
        }

        @Override
        public View getView(ViewGroup container, int position) {
            View view = View.inflate(context, R.layout.item_lunbo, null);
            ImageView iv_img = (ImageView) view.findViewById(R.id.imv_lunbo);

            Glide.with(context)
                    .load(HttpIP.Base_IpIMage+imgs.get(position).getSliderImg())
                    .placeholder(R.drawable.mo_lunbo) //等待时的图片
                    .error(R.drawable.mo_lunbo)       //加载失败的图片
                    .dontAnimate()
                    .into(iv_img);
            return view;
        }

        @Override
        public int getRealCount() {
            return imgs.size();
        }

    }
}
